package com.chx.interceptor;

import com.chx.constant.JwtClaimsConstant;
import com.chx.context.BaseContext;
import com.chx.entity.Permissions;
import com.chx.entity.Users;
import com.chx.mapper.PermissionMapper;
import com.chx.mapper.UserMapper;
import com.chx.properties.JwtProperties;
import com.chx.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author cp-月入过万
 * @Date 2025/5/29
 * jwt令牌校验的拦截器
 */

@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());
        String url =  request.getRequestURI();
        //拆分url
        String permissionCode = url.split("/")[2];
        String page = "";
        if(url.split("/").length > 3)
            page = url.split("/")[3];
        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前员工id：{}", empId);

            Users users = userMapper.getById(empId);
            List<Permissions> permissions = permissionMapper.getPermissionById(users.getRoleId());

            List<String> permissionCodes = permissions.stream().map(Permissions::getPermissionCode).collect(Collectors.toList());

            //将当前登录用户的id存入ThreadLocal
            BaseContext.setCurrentId(empId);
            if (permissionCodes.contains(permissionCode) || Objects.equals(page, "page") ||Objects.equals(page, "list")) {
                //3、通过，放行
                return true;
            }else {
                //4、没有权限 ，响应405状态码
                response.setStatus(405);
                return false;
            }

        } catch (Exception ex) {
            //5、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
